import { OpenAPIV3 } from 'openapi-types';
import type { Plugin } from 'vue';

import { api as OdinWebApi } from '@/request/odin-api-v1';
import odinDoc from '@/request/odin-api-v1/api.json';
// eslint-disable-next-line import/no-cycle
import { TauriHttpRequest } from './request';
import { initClientVerInfo } from './interceptors';
import { client as axiosClient } from './client';
import getBaseHost from './host';

let odinApi: OdinWebApi;

export async function initApi() {
  await initClientVerInfo();
  const host = await getBaseHost();
  odinApi = new OdinWebApi({ BASE: host }, TauriHttpRequest);
  const req = odinApi.request;
  if (req instanceof TauriHttpRequest) {
    req.doc = odinDoc as OpenAPIV3.Document;
  }
  return odinApi;
}

const $api: Plugin = {
  install(app) {
    app.config.globalProperties.$api = odinApi;
  },
};

export {
  odinApi,
  axiosClient,
  $api,
};

// 一些类型运算
export type ArticleInfo = Required<Awaited<ReturnType<typeof odinApi.default.getArticleLists>>>['data']['news'][number];
export type GameItem = Required<Awaited<ReturnType<typeof odinApi.default.getAllSupportedGames>>>['data']['games'][number];
export type MyGameItem = Required<Awaited<ReturnType<typeof odinApi.default.getMyFavoriteGames>>>['data']['games'][number];
export type Retrieval = Required<Awaited<ReturnType<typeof odinApi.default.getRetrieval>>>['data']['game'][number];

declare module 'vue' {
  interface ComponentCustomProperties {
    $api: OdinWebApi;
  }
}
